package com.hsurosy.hsuchain.nft.order.domain.entity.statemachine;

import com.hsurosy.hsuchain.nft.api.order.constant.TradeOrderEvent;
import com.hsurosy.hsuchain.nft.api.order.constant.TradeOrderState;
import com.hsurosy.hsuchain.nft.base.statemachine.BaseStateMachine;

/**
 * 订单状态机类
 *
 * @Author Hsu琛君珩
 * @Date 2024-10-05 17:05
 * @Description
 * @Version: v1.0.0
 */
public class OrderStateMachine extends BaseStateMachine<TradeOrderState, TradeOrderEvent> {

    /**
     * 单例模式的实例
     */
    public static final OrderStateMachine INSTANCE = new OrderStateMachine();

    // 构造函数块，用于定义订单状态机的状态转换规则
    {
        // 从创建状态到确认状态的转换
        putTransition(TradeOrderState.CREATE, TradeOrderEvent.CONFIRM, TradeOrderState.CONFIRM);

        // 从确认状态到已支付状态的转换
        putTransition(TradeOrderState.CONFIRM, TradeOrderEvent.PAY, TradeOrderState.PAID);

        // 库存预扣减成功，但未真正扣减成功时，可以支付或取消
        putTransition(TradeOrderState.CREATE, TradeOrderEvent.PAY, TradeOrderState.PAID);
        putTransition(TradeOrderState.CREATE, TradeOrderEvent.CANCEL, TradeOrderState.CLOSED);
        putTransition(TradeOrderState.CREATE, TradeOrderEvent.TIME_OUT, TradeOrderState.CLOSED);

        // 已支付后再确认，状态保持为已支付
        putTransition(TradeOrderState.PAID, TradeOrderEvent.CONFIRM, TradeOrderState.PAID);

        // 确认状态下可以取消或超时关闭
        putTransition(TradeOrderState.CONFIRM, TradeOrderEvent.CANCEL, TradeOrderState.CLOSED);
        putTransition(TradeOrderState.CONFIRM, TradeOrderEvent.TIME_OUT, TradeOrderState.CLOSED);

        // 已支付状态下可以完成订单
        putTransition(TradeOrderState.PAID, TradeOrderEvent.FINISH, TradeOrderState.FINISH);
    }
}
